package jzOffer;

/**
 * @author 郝文雪
 * @date 2022/7/15 11:40
 * @Description Test
 */
public class Num21 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(n<0||head==null){
            return head;
        }
        ListNode dummyHead=new ListNode(-1);
        dummyHead.next=head;
        ListNode low=dummyHead, fast=dummyHead;
        for (int i = 0; i < n; i++) {
            if(fast==null){
                return null;
            }
            fast=fast.next;
        }
        while(fast!=null && fast.next!=null){
            low=low.next;
            fast=fast.next;
        }
        //此时low是待删除结点的前驱结点
        ListNode node=low.next;
        low.next=node.next;
        node.next=null;
        return dummyHead.next; //一定要返回虚拟头节点的next 如果返回head,头结点可能已经被删除了
    }
}
